package cn.tedu.egarticle.controller;

import cn.tedu.egarticle.base.response.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/v1/file/")
@Api(tags = "02.文件上传模块")
public class UploadController {

    @PostMapping("upload")
    @ApiOperation(value = "文件上传功能")
    @ApiOperationSupport(order = 10)
    public JsonResult upload(MultipartFile file) {
        String filename = file.getOriginalFilename();
        log.debug("初始名称：" + filename);
        String str = filename.substring(filename.lastIndexOf("."));
        log.debug("后缀名：" + str);
        filename = UUID.randomUUID() + str;
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        log.debug("日期路径：" + datePath);
        String staticPath = "D:/newFiles";
        log.debug("静态路径： " + staticPath);
        File dirPath = new File(staticPath + datePath);
        log.debug("目录路径： " + dirPath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        String filePath = staticPath + datePath + filename;
        log.debug("完整路径： " + filePath);
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JsonResult.ok(datePath + filename);
    }

}
